
#include <iostream>

#include <string>
#include <cstring>
#include <unistd.h>
#include <unordered_map>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

// 用户
class User
{
public:
    User(const string &ip, const uint16_t port)
        : _ip(ip), _port(port)
    {
    }
    string getip()
    {
        return _ip;
    }
    uint16_t getport()
    {
        return _port;
    }
    ~User()
    {
    }

private:
    string _ip;
    uint16_t _port;
};

// 在线用户
class OnlineUser
{
public:
    OnlineUser()
    {
    }
    void addUser(const string &ip, const uint16_t &port)
    {
        string id = ip + "-" + to_string(port);
        users.insert(make_pair(id, User(ip, port)));
    }
    void delUser(const string &ip, const uint16_t &port)
    {
        string id = ip + "-" + to_string(port);
        users.erase(id);
    }
    bool isonline(const string &ip, const uint16_t &port)
    {
        string id = ip + "-" + to_string(port);
        if (users.find(id) == users.end())
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    void boardcastMessage(int sockfd, const string &ip, const uint16_t &port, const string &message)
    {
        for (auto &user : users)
        {
            string respon_message;
            string id = ip + "-" + to_string(port); // 注意：转发消息的时候，转发的消息是发送该信息的客户端id；转发的对象是所有在线用户
            respon_message = id + " # " + message;

            struct sockaddr_in client;
            bzero(&client, 0);
            client.sin_family = AF_INET;
            client.sin_port = htons(user.second.getport());
            client.sin_addr.s_addr = inet_addr(user.second.getip().c_str());
            sendto(sockfd, respon_message.c_str(), respon_message.size(), 0, (struct sockaddr *)&client, sizeof(client));
        }
    }
    ~OnlineUser()
    {
    }

private:
    unordered_map<string, User> users;
};